package com.cuz.series.linklist;

public class 链表8合并两个有序链表 {

    public static void main(String[] args) {
        ListNode node1 = ListNode.of1(1, 2, 4,5);
        ListNode node2 = ListNode.of1(1, 3, 4);
        mergeTwoLists1(node1,node2).print();
    }
    public static ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        ListNode preHead = new ListNode();
        ListNode tail = preHead;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                tail.next = list1;
                list1 = unlinkReturnNext(list1);
            } else {
                tail.next = list2;
                list2 = unlinkReturnNext(list2);
            }
            tail = tail.next;
        }
        tail.next = list1 == null ? list2 : list1;
        return preHead.next;
    }

    private static ListNode unlinkReturnNext(ListNode node) {
        ListNode next = node.next;
        node.next = null;
        return next;
    }


}
